import { Form, Input, Modal, Select, Upload, type GetProp, type UploadProps, TreeSelect } from "antd";
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { useEffect, useImperativeHandle, useState } from "react";

import storage from "../../../utils/storage";
import { message } from "../../../utils/AntdGlobal";
import type { IAction } from "../../../types/modal";
import type { Dept, Role, User } from "../../../types/api";
import api from "../../../api";

export default function CreateUser(props: any) {
    const [form] = Form.useForm()
    const [visible, setVisible] = useState(false)
    const [action, setAction] = useState<IAction>('create')
    const [Img, setImg] = useState('')
    const [loading, setLoading] = useState(false)
    const [deptList, setDeptList] = useState<Dept.deptItem[]>([])
    const [roleList, setRoleList] = useState<any>([])

    useEffect(() => {
        getDeptList()
        getAllRoleList()
    }, [])

    const getDeptList = async () => {
        const data = await api.getDeptList()
        setDeptList(data)
    }

    const getAllRoleList = async () => {
        const data = await api.getAllRoleList()
        const newData = data.map((item, index) => {
            return { value: index + 1, key: item._id, label: item.roleName }
        })
        setRoleList(newData)
    }

    useImperativeHandle(props.ref, () => {
        return {
            open
        }
    })

    const open = (type: IAction, data?: User.userItem) => {
        setVisible(true)
        setAction(type)
        if (type === 'edit' && data) {
            form.setFieldsValue(data)
            setImg(data.userImg)
        }
    }
    const token = storage.get('token')

    type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

    const handleSubmit = async () => {
        const valid = await form.validateFields()
        if (valid) {
            const params = {
                ...form.getFieldsValue(),
                userImg: Img
            }
            if (action === 'create') {
                await api.createUser(params)
                message.success('创建成功')
            } else if (action === 'edit') {
                await api.editUser(params)
                message.success('修改成功')
            }
            handleCancel()
            props.update()
        }
    }
    const handleCancel = () => {
        setVisible(false)
        setImg('')
        form.resetFields()
    }

    //上传前 校验图片格式 校验图片大小
    const beforeUpload = (file: FileType) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
            return false
        }
        const isLt500K = file.size / 1024 / 1024 < 0.5;
        if (!isLt500K) {
            message.error('Image must smaller than 500K!');
        }
        return isJpgOrPng && isLt500K;
    };
    const handleChange: UploadProps['onChange'] = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            setLoading(false)
            if (info.file.response.code === 0) {
                setImg(info.file.response.data.file.replace('cc', 'com.cn'))
            } else {
                message.error(info.file.response.msg)
            }
        } else if (info.file.status === "error") {
            message.error('服务器异常，请稍后重试')
        }
    }

    return (
        <Modal
            title={action === 'create' ? '创建用户' : '编辑用户'}
            width={800}
            open={visible}
            onOk={handleSubmit}
            onCancel={handleCancel}
            okText="确定"
            cancelText="取消"
        >
            <Form
                form={form}
                labelCol={{ span: 4 }}
                labelAlign="right"
                initialValues={{ state: 1, role: 3 }}
            >
                <Form.Item name="userId" hidden>
                    <Input />
                </Form.Item>
                <Form.Item label='用户名称' name='userName'
                    rules={[
                        { required: true, message: '请输入用户名称' },
                        { min: 5, max: 10, message: "用户名称最少5个字符，最大10个字符" }
                    ]}>
                    <Input placeholder="请输入用户名称" />
                </Form.Item>
                <Form.Item label='用户邮箱' name='userEmail'
                    rules={[
                        { required: true, message: '请输入用户邮箱' },
                        { type: "email", message: "请输入正确的邮箱" }
                    ]}>
                    <Input placeholder="请输入用户邮箱" disabled={action === 'edit'} />
                </Form.Item>
                <Form.Item label='手机号' name='mobile'
                    rules={[
                        { len: 11, message: "手机号必须为11位数字" },
                        { pattern: /1[1-9]\d{9}/, message: "请输入正确的手机号格式" }
                    ]}
                >
                    <Input type="number" placeholder="请输入手机号" />
                </Form.Item>
                <Form.Item label='部门' name='deptId' rules={[{ required: true, message: '请选择部门' }]}>
                    <TreeSelect
                        treeData={deptList}
                        allowClear
                        treeDefaultExpandAll
                        showCheckedStrategy={TreeSelect.SHOW_ALL}
                        fieldNames={{ label: 'deptName', value: '_id' }}
                        placeholder="请选择部门" />
                </Form.Item>
                <Form.Item label='岗位' name='job'>
                    <Input placeholder="请输入岗位" />
                </Form.Item>
                <Form.Item label='状态' name='state'>
                    <Select style={{ width: 120 }}>
                        <Select.Option value={1}>在职</Select.Option>
                        <Select.Option value={2}>离职</Select.Option>
                        <Select.Option value={3}>试用期</Select.Option>
                    </Select>
                </Form.Item>
                <Form.Item label='系统角色' name='role'>
                    <Select
                        options={roleList}
                        placeholder="请输入角色" />
                </Form.Item>
                <Form.Item label="用户头像">
                    <Upload
                        listType="picture-circle"
                        showUploadList={false}
                        headers={
                            {
                                Authorization: 'Bearer ' + token,
                                icode: '11E0EEDC543C1BC7'
                            }
                        }
                        action='/api/users/upload'
                        beforeUpload={beforeUpload}
                        onChange={handleChange}
                    >
                        {
                            Img ? <img src={Img} style={{ width: '100%', borderRadius: '100%' }} /> : (<div>{loading ? <LoadingOutlined /> : <PlusOutlined />}
                                <div>上传头像</div> </div>)
                        }
                    </Upload>
                </Form.Item>
            </Form>
        </Modal>
    )
}